package com.why.config;

import com.why.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();
        if (null == cookies) {
            return false;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("cookieUser")) {
                    HashMap<String, Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                    User user = (User) map.get("user");
                    if (null != user) {
                        Date date= (Date) map.get("time");
                        long temp=new Date().getTime()-date.getTime();
                        System.out.println("-------------------------------------------->"+temp);
                        if (temp>15*60*1000){
                            redisTemplate.opsForValue().set(cookie.getValue(),map,30, TimeUnit.MINUTES);
                            cookie.setMaxAge(30*60);
                            map.put("time",new Date());
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
